//--------------在线下单 出口
/* 1  */
function showErrorShowDiv(errorMessage, errorDetail) {
    $('#errorShowDiv').dialog('setTitle', '操作失败').dialog('open');
    $('#errorShowDiv').parent().css("top", "2px").next().css("display", "none");
    $("#errorDetailDiv").hide();
    $('#errorMessage').html(errorMessage);
    $('#errorDetail').html(errorDetail.replace(" ", "&nbsp;"));
}
function showErrorDetail() {
    $("#errorDetailDiv").show();
}
function closeErrorShowDiv() {
    $('#errorShowDiv').dialog('close');
    $('#errorDetail').html('');
    $('#errorMessage').html('');
}

/* 2 */
function showNoteShowDiv(noteMessage) {
    closeNoteShowDiv();
    $('#noteShowDiv').dialog('setTitle', '提示').dialog('open');
    $('#noteShowDiv').parent().css("top", "2px").next().css("display", "none");
    $('#noteShowDivDiv').html(noteMessage);
}

function closeNoteShowDiv() {
    $('#noteShowDiv').dialog('close');
    $('#noteShowDivDiv').html('');
}

/* 3 */
$(function () {
    $("#hgImportFile").each(function () {
        if ($(this).val() == "") {
            $(this).parents(".uploader").find(".filename").val("没有选择文件...");
        }
    });

});
function fileOnchange(o) {
    $(o).parents(".uploader").find(".filename").val($(o).val());
}

/*  4  */
$(function () {
    //parent.toLeftMenu('4');
})
//打印下来控件
$('#nav-menu .ans_left > li').hover(function () {
    $(this).find('.children').animate({opacity: 'show', height: 'show'}, 200);
    $(this).find('.xialaguang').addClass('navhover');
}, function () {
    $('.children').stop(true, true).hide();
    $('.xialaguang').removeClass('navhover');
});

/*   5  */
//设置页面滚动条高度
$(document).ready(function () {
    function resize() {
        //$("#bao").height($(document.body).height());
        $("#nr_x_b").height($(document.body).height() - $("#nr_x_b").offset().top);

    }

    $(window).resize(function () {
        resize();
    });
    resize();
})

/* 6 */

function Len(str) {
    var i, sum;
    sum = 0;
    for (i = 0; i < str.length; i++) {
        if ((str.charCodeAt(i) >= 0) && (str.charCodeAt(i) <= 255)) {
            sum = sum + 1;
        } else {
            sum = sum + 2;
        }
    }
    return sum;
}

$(document).ready(function () {
    $("#myForm").validate({
                              success: function (label) {
                                  label.html("&nbsp;").addClass("checked");
                              }
                          });

    jQuery.validator.addMethod("decimal", function (value, element) {
        var decimal = /^-?\d+(\.\d+)?$/;
        return this.optional(element) || (decimal.test(value));
    }, $.validator.format("请正确输入金额!"));

    jQuery.validator.addMethod("int", function (value, element) {
        var decimal = /^[0-9]*[1-9][0-9]*$/;
        return this.optional(element) || (decimal.test(value));
    }, $.validator.format("请输入整数!"));

    jQuery.validator.addMethod("inta", function (value, element) {
        var decimal = /^[0-9]*[1-9][0-9]*$/;
        return this.optional(element) || (decimal.test(value) && value <= 60);
    }, $.validator.format("请输入一个1-60的整数!"));

    jQuery.validator.addMethod("maxlengthTwenty", function (value, element) {
        return this.optional(element) || ((Len(value) <= 45));
    }, $.validator.format("长度不能大于45（汉字算两个)"));

    jQuery.validator.addMethod("maxlengthRemark", function (value, element) {
        return this.optional(element) || ((Len(value) <= 255));
    }, $.validator.format("长度不能大于255（汉字算两个)"));

    jQuery.validator.addMethod("max100000", function (value, element) {
        return this.optional(element) || (value <= 100000);
    }, $.validator.format("不能大于100000"));

    jQuery.validator.addMethod("length10", function (value, element) {
        return this.optional(element) || (value.length == 10);
    }, $.validator.format("长度只能为10"));

    jQuery.validator.addMethod("jpgFile", function (value, element) {
        var temp = value.substring(value.length - 4, value.length);
        return this.optional(element) || (temp == ".jpg");
    }, $.validator.format("*.jpg"));

    jQuery.validator.addMethod("ftN", function (value, element) {
        var decimal = /^[0-9]*[1-9][0-9]*$/;
        return this.optional(element) || (decimal.test(value) && Len(value) == 14);
    }, $.validator.format("输入14位卡号"));
    jQuery.validator.addMethod("UID", function (value, element) {
        var decimal = /^[A-Za-z0-9]*[A-Za-z0-9]*$/;
        return this.optional(element) || (decimal.test(value) && Len(value) == 18);
    }, $.validator.format("18位身份证号码"));
    jQuery.validator.addMethod("mobile", function (value, element) {
        var length = value.length;
        var mobile = /^((13[0-9])|(15[0-9])|(18[0-9])|(14[0-9])|(17[0-9]))\d{8}$/;
        return this.optional(element) || (length == 11 && mobile.test(value));
    }, "手机号码格式错误");
    jQuery.validator.addMethod("maxlength", function (value, element, param) {
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) || (length <= param);
    }, $.validator.format("长度不能大于 {0} , 一个中文长度为2"));

    jQuery.validator.addMethod("anLength", function (value, element, param) {
        var anLength = /^[A-Za-z0-9]+$/;
        var length = this.getLength($.trim(value), element);
        return this.optional(element) || (anLength.test(value) && length >= param[0]
                                          && length <= param[1]);
    }, $.validator.format("请输入一个长度介于{0}和 {1}之间的数字或字符串!"));

    jQuery.validator.addMethod("nLength", function (value, element, param) {
        var nLength = /^[0-9]+$/;
        var length = this.getLength($.trim(value), element);
        return this.optional(element) || (nLength.test(value) && length >= param[0]
                                          && length <= param[1]);
    }, $.validator.format("请输入一个长度介于{0}和 {1}之间的数字!"));
});

jQuery.validator.addMethod("maxlength_T", function (value, element, param) {
    return this.optional(element) || ((Len(value) <= param));
}, $.validator.format("长度不能大于{0}（汉字算两个)"));

jQuery.validator.addMethod("box", function (value, element) {
    var temp = /^[a-zA-Z]{4}[0-9]{7}$/;
    return this.optional(element) || (temp.test(value));
}, $.validator.format("请输入4位字母加7位数字的字符串！"));

function ajax4Biz(params, url, callback, beforeSend, isAsync, type) {
    var retVal = '';
    $.ajax({
               url: url,
               type: type ? type : "POST",
               data: params,
               dataType: "text",
               cache: false,
               async: (typeof (isAsync) == "undefined") ? true : isAsync,
               beforeSend: function () {
                   if (beforeSend) {
                       beforeSend();
                   }
               },
               success: function (data) {
                   if (data) {
                       if (callback) {
                           retVal = callback(data);
                       }
                   }
               }
           });
    return retVal;
}

$(document).ready(function () {
    if ($("#initjquery").val() == "1") {
        return;
    }
    $("#initjquery").val("1");
    var mess = 'null';
    if (mess != "" && mess != null && mess != 'null') {
        alert(mess);
    }
});

$(document).ready(function () {
    if ($("[datepicker]")) {
        $("[datepicker]").each(function (index) {
            if ($(this).attr('datepicker')) {
                var id = $(this).attr('id');
                if (id) {
                    $('#' + id).focus(function () {
                        WdatePicker(
                            {
                                isShowClear: false,
                                isShowToday: false,
                                isShowClear: false,
                                isShowOthers: true,
                                dateFmt: getDateFmt($(this).attr('datepicker')),
                                readOnly: true
                            }
                        );
                    });

                    $('#' + id).addClass('Wdate');
                }
            }
        });
    }

});

function getDateFmt(obj) {
    if (obj == "time") {
        return 'yyyy-MM-dd HH:mm:ss';
    } else {
        return 'yyyy-MM-dd';
    }
}

var explorer_type = {};

var userAgent_toLow = navigator.userAgent.toLowerCase();

var explorer_type_str;

(explorer_type_str = userAgent_toLow.match(/msie ([\d.]+)/)) ? explorer_type.ie =
    explorer_type_str[1] :

(explorer_type_str = userAgent_toLow.match(/firefox\/([\d.]+)/)) ? explorer_type.firefox =
    explorer_type_str[1] :

(explorer_type_str = userAgent_toLow.match(/chrome\/([\d.]+)/)) ? explorer_type.chrome =
    explorer_type_str[1] :

(explorer_type_str = userAgent_toLow.match(/opera.([\d.]+)/)) ? explorer_type.opera =
    explorer_type_str[1] :

(explorer_type_str = userAgent_toLow.match(/version\/([\d.]+).*safari/))
    ? explorer_type.safari = explorer_type_str[1] : 0;

if (document.all) {	//阻止IE8下javascript:void(0)触发beforeunload事件
    $("a[href='javascript:void(0)']").live("click", function (e) {
        e.preventDefault();
    });
}

/****************************************/
/**
 * 时间对象的格式化
 */
Date.prototype.format = function (format) {
    /*
     * format="yyyy-MM-dd hh:mm:ss";
     */
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    }
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4
                                                                            - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
}
//{"date":"3","day":"2","hours":"0","minutes":"0","month":"0","seconds":"0","time":"1325520000000","timezoneOffset":"-480","year":"112"}
function toDate(obj) {
    var date = new Date();
    date.setTime(obj.time);
    date.setHours(obj.hours);
    date.setMinutes(obj.minutes);
    date.setSeconds(obj.seconds);
    return date.format("yyyy-MM-dd");
}

/***************没保存离开页面提醒********************/


//	window.onload = initFileds();
/* 	$(document).ready(function() {
 initFileds();
 });  */
$(window).load(function () {
    initFileds();
});
// 页面编辑数据
var inputsData;
var textareasData;
var selectsData;

// 记录下表单中的原始值
function initFileds() {
    try {
        var inputs = $("#myForm input[name]");
        var textareas = $("#myForm textarea[name]");
        var selects = $("#myForm select[name]");
        inputsData = new Array(inputs.length);
        for (var i = 0; i < inputs.length; i++) {
            inputsData[i] = inputs[i].value;
            if (inputs[i].type == "radio") {
                inputsData[i] = inputs[i].checked;
            }
        }
        textareasData = new Array(textareas.length);
        for (var i = 0; i < textareas.length; i++) {
            textareasData[i] = textareas[i].value;
        }
        selectsData = new Array(selects.length);
        for (var i = 0; i < selects.length; i++) {
            selectsData[i] = selects[i].value;
        }
    }
    catch (e) {

    }
}

/* 判断表单中值是否被修改了
 * submitCommand 表单有改动时,执行的javascript代码
 */
function checkModification() {
    var hasBeenChanged = false;
    try {
        var inputs = $("#myForm input[name]");
        var textareas = $("#myForm textarea[name]");
        var selects = $("#myForm select[name]");

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type == "radio" && (inputs[i].checked != inputsData[i])) {
                hasBeenChanged = true;
                return hasBeenChanged;
                //    inputsData[i]=inputs[i].checked;
            }
            if (inputs[i].type != "radio" && inputsData[i] != inputs[i].value) {
                if (inputs[i].name != "actionType") {
                    hasBeenChanged = true;
                    return hasBeenChanged;
                }
                //   inputsData[i]=inputs[i].value;
            }
        }
        for (var i = 0; i < textareas.length; i++) {
            if (textareasData[i] != textareas[i].value) {
                hasBeenChanged = true;
                return hasBeenChanged;
                //   textareasData[i]=textareas[i].value;
            }
        }
        for (var i = 0; i < selects.length; i++) {
            if (selectsData[i] != selects[i].value) {
                hasBeenChanged = true;
                //   selectsData[i]=selects[i].value;
                return hasBeenChanged;
            }
        }
    } catch (e) {
        // TODO: handle exception
    }
    return hasBeenChanged;
}
var listentFlagForBeforeunload = 1;
$(window).bind('beforeunload', function () {
    //	var id = $("#jyjyId").val();

    if (checkModification() && listentFlagForBeforeunload) {

        return "您输入的内容尚未保存，确定离开此页面吗？";
    }
    listentFlagForBeforeunload = 1;
});

function doOnUnload(seflIframeId) {
    parent.returnOldTabData(seflIframeId);
    // sleep(500);
}

var islistentIgnoreBeforeunload = 0;
if (navigator.appName == "Microsoft Internet Explorer" && (navigator.appVersion.match(/9./i)
                                                           == "9."
                                                           || navigator.appVersion.match(
        /8./i) == "8.")) {
    islistentIgnoreBeforeunload = 1;
}

function ignoreBeforeunload() { //用于防止IE9触发beforeunload
    if (islistentIgnoreBeforeunload) {
        listentFlagForBeforeunload = 0;
    }

}

function bindPanelCloseIgnoreBeforeunload() {
    $("a[class='panel-tool-close']").unbind("click", ignoreBeforeunload).bind("click",
                                                                              ignoreBeforeunload);
}

function IsURL(str_url) {
    var strRegex = '^((https|http|ftp|rtsp|mms)?://)'
                   + '?(([0-9a-z_!~*\'().&=+$%-]+: )?[0-9a-z_!~*\'().&=+$%-]+@)?' //ftp的user@
                   + '(([0-9]{1,3}.){3}[0-9]{1,3}' // IP形式的URL- 199.194.52.184
                   + '|' // 允许IP和DOMAIN（域名）
                   + '([0-9a-z_!~*\'()-]+.)*' // 域名- www.
                   + '([0-9a-z][0-9a-z-]{0,61})?[0-9a-z].' // 二级域名
                   + '[a-z]{2,6})' // first level domain- .com or .museum
                   + '(:[0-9]{1,4})?' // 端口- :80
                   + '((/?)|' // a slash isn't required if there is no file name
                   + '(/[0-9a-z_!~*\'().;?:@&=+$,%#-]+)+/?)$';
    var re = new RegExp(strRegex);
    //re.test()
    if (re.test(str_url)) {
        return (true);
    } else {
        return (false);
    }
}

//===========================enter 替换 tab
$(document).ready(function () {
    $(':input:text:first').focus();
    $(':input:enabled').addClass('enterIndex');
    // get only input tags with class data-entry
    textboxes = $('.enterIndex');
    // now we check to see which browser is being used
    var userAgent = navigator.userAgent;     //取得浏览器的userAgent字符串
    if ($.browser.mozilla) {
        if (userAgent.indexOf("Firefox") > -1) {//火狐
            $(textboxes).bind('keydown', CheckForEnter);
        } else {
            var browser = navigator.appName;
            var b_version = navigator.appVersion;
            var version = b_version.split(";");
            var trim_Version = version[1].replace(/[ ]/g, "");
            //IE11
            if (browser == "Netscape" && trim_Version == "WOW64") {
                $(textboxes).bind('keydown', CheckForEnter);
            } else {
                $(textboxes).bind('keypress', CheckForEnter);
            }
        }
    } else {
        $(textboxes).bind('keydown', CheckForEnter);
    }
});
function EnterTransTab(ownerObj) {
    var i = $('.enterIndex').index(ownerObj) + 1;
    var n = $('.enterIndex').length;
    if (i < n - 1) {
        if (ownerObj.attr('type') != 'radio') {
            NextDOM($('.enterIndex'), i);
        } else {
            var last_radio = $('.enterIndex').index(
                $('.enterIndex[type=radio][name=' + ownerObj.attr('name') + ']:last'));
            NextDOM($('.enterIndex'), last_radio);
        }
    }

    return false;
}
function CheckForEnter(event) {
    if (event.keyCode == 13 && $(this).attr('type') != 'button' && $(this).attr('type')
                                                                   != 'submit'
        && $(this).attr('type') != 'textarea' && $(this).attr('type') != 'reset') {
        /*
         console.log($(document.activeElement));
         console.log($(document.activeElement).next(".enterIndex"));
         $(document.activeElement).next(".enterIndex").focus();
         */
        var i = $('.enterIndex').index($(this));
        var n = $('.enterIndex').length;
        if (i < n - 1) {
            if ($(this).attr('type') != 'radio') {
                NextDOM($('.enterIndex'), i);
            } else {
                var last_radio = $('.enterIndex').index(
                    $('.enterIndex[type=radio][name=' + $(this).attr('name')
                      + ']:last'));
                NextDOM($('.enterIndex'), last_radio);
            }
        }

        return false;
    }
}
function NextDOM(myjQueryObjects, counter) {
    var objJq = myjQueryObjects.eq(counter + 1);
    var objectDom = objJq[0];
    var isComboboxReadOnly = 0;

    try {
        if (objectDom.hasAttribute("autocomplete") == true && objJq.prev("span").children(
                "a[class*='textbox-icon-disabled']").length > 0) {
            isComboboxReadOnly = 1;
        }
    } catch (e) {
        alert(e.message);
    }
    if (objectDom.disabled || objectDom.type == 'hidden'
        || objectDom.style.display == 'none'
        || (objectDom.readOnly && objectDom.hasAttribute("autocomplete") == false  )
        || isComboboxReadOnly
    ) {//自定义下拉框的判断

        NextDOM(myjQueryObjects, counter + 1);
    } else {

        objJq.trigger('focus');
        //objectDom.focus();
    }
}

/*document.onkeydown=function enterToTab(){
 alert("click");
 if(event.srcElement.type != 'submit' && event.srcElement.type!="image" && event.srcElement.type != 'textarea'&& event.keyCode == 13){
 event.keyCode = 9;
 alert("click enter");
 }
 }*/

/**按钮权限设置是否显示*/
function checkAuthority() {
    var urlStr = ';/admin/sys_index.do;/admin/sys_left.do;/admin/sys_right.do;/admin/sys_top.do;/admin/bamain_getallData.do;/admin/admin_info.do;/admin/entryInspect_inspect.do;/admin/exportDeclare_queryById.do;/admin/exportInspect_queryById.do;/admin/optionvalue_editById.do;/admin/optionvalue_queryByID.do;/admin/optionvalue_delete.do;/admin/baseData_loadBaseData.do;/admin/baseData_checkValue.do;/admin/baseData_loadSecondData.do;/admin/baseData_linkData.do;/admin/report_importGood.do;/admin/report_importExportHG.do;/admin/baseData_loadBaseDataByTable.do;/admin/report_importBox.do;/admin/edoc_delete.do;/admin/edoc_save.do;/admin/edoc_list.do;http://www.singlewindow.gz.cn/cargodecl;/admin/entryDeclareAndInspect_query.do;/admin/entryDeclareAndInspect_save.do;/admin/entryDeclareAndInspect_upload.do;/admin/entryDeclareAndInspect_declare.do;/admin/entryDeclare_queryByGjhAndGjglmm.do;/admin/entryInspect_queryByGjhAndGjglmm.do;/admin/entryDeclareAndInspect_query.do;/admin/openQP.do;/admin/report_getJyjyReportUrl.do;/admin/copyGjNewOne.do;/admin/entryDeclare_customs.do;/admin/entryDeclare_save.do;/admin/entryDeclare_upload.do;/admin/entryInspect_queryByGjhAndGjglmm.do;/admin/dataQuery_queryBygjh.do;/admin/entryDeclare_customs.do;/admin/copyHgNewOne.do;/admin/openQP.do;/admin/report_getHgReportUrl.do;/admin/entryInspect_inspect.do;/admin/entryInspect_save.do;/admin/entryInspect_declare.do;/admin/entryDeclare_queryByGjhAndGjglmm.do;/admin/dataQuery_queryBygjh.do;/admin/entryInspect_inspect.do;/admin/copyJyjyNewOne.do;/admin/report_getJyjyReportUrl.do;/admin/exportDeclareAndInspect_query.do;/admin/exportDeclareAndInspect_save.do;/admin/exportDeclareAndInspect_upload.do;/admin/exportDeclareAndInspect_declare.do;/admin/exportDeclare_queryByGjhAndGjglmm.do;/admin/exportInspect_queryByGjhAndGjglmm.do;/admin/exportDeclareAndInspect_query.do;/admin/copyGjNewOne.do;/admin/openQP.do;/admin/report_getHgReportUrl.do;/admin/exportDeclare_customs.do;/admin/exportDeclare_save.do;/admin/exportDeclare_upload.do;/admin/exportInspect_queryByGjhAndGjglmm.do;/admin/dataQuery_queryBygjh.do;/admin/exportDeclare_customs.do;/admin/copyHgNewOne.do;/admin/openQP.do;/admin/report_getHgReportUrl.do;/admin/exportInspect_exportInspect.do;/admin/exportInspect_save.do;/admin/exportInspect_declare.do;/admin/exportDeclare_queryByGjhAndGjglmm.do;/admin/dataQuery_queryBygjh.do;/admin/exportInspect_exportInspect.do;/admin/copyJyjyNewOne.do;/admin/report_getJyjyReportUrl.do;/admin/dataQuery_list.do;/admin/dataQuery_queryBygjh.do;/admin/entryDeclare_queryById.do;/admin/entryInspect_queryById.do;/admin/dataQuery_queryReceivequeue.do;/admin/dataQuery_queryReceiptRecord.do;/admin/dataQuery_queryDeclRecord.do;/admin/dataQuery_queryContainer.do;/admin/dataQuery_queryDeclPacnRecord.do;/admin/dataQuery_delete.do;/admin/dataQuery_refresh.do;/admin/dataQuery_list.do;/admin/dataQuery_clear.do;/admin/optionvalue_list.do;/admin/optionvalue_list.do;/admin/optionvalue_addApply.do;/admin/basicinfo_list.do;/admin/basicinfo_saveOrUpdate.do;/admin/dataQuery_countCompanyData.do;';
    $("[showfunction]").each(function () {
        if ($(this).attr('showfunction') != '' && urlStr.indexOf(
                ';/admin/' + $(this).attr('showfunction') + ';') != -1) {
            $(this).removeAttr("showfunction");
        }
    });
}


